#include "stdafx.h"
#include <Strsafe.h>
#include <Shlwapi.h>
#include <wchar.h>
#include "Registry.h"
#include "HttpF2.h"

#pragma comment(lib,"Shlwapi.lib")

HttpF2::HttpF2(PTSTR sn,ushort ver):Http2(agent(sn,ver)){
	checksum=0;
	version=0;
	try{
		MachineOrUser reg(L"Software\\Phoxell\\xync");
		host=reg.get(L"host",L"www.phoxell.com");
	}catch(int){
		host=new String(L"www.phoxell.com");
	}
	name=host->Ptstr();
	PTCHAR p=StrChr(name,L':');
	if(p){
		*p=0;
		p++;
		swscanf_s(p,L"%d",&port);
	}else port=INTERNET_DEFAULT_HTTP_PORT;
}
HttpF2::~HttpF2(void){
	delete host;
}
PTSTR HttpF2::agent(PTSTR sn,ushort ver){
	uint m=ver >> 8;
	uint n=ver & 0xff;
	StringCbPrintf(agentBuf,sizeof(agentBuf),
		_T("XYNC/0.5 (Windows NT 5.1) SerialNumber=%s, Firmware=%d.%d"),sn,m,n);
	return agentBuf;
}
void HttpF2::onCallback(HINTERNET inernet,uint status,LPVOID info,uint length){
	if(status==WINHTTP_CALLBACK_STATUS_REDIRECT){
		uint len=0;
		WinHttpQueryHeaders(inernet,WINHTTP_QUERY_RAW_HEADERS_CRLF,
			WINHTTP_HEADER_NAME_BY_INDEX,NULL,&len,WINHTTP_NO_HEADER_INDEX);
		if(len){
			if(TCHAR* buf=(TCHAR*)malloc(len)){
				WinHttpQueryHeaders(inernet,WINHTTP_QUERY_RAW_HEADERS_CRLF,
					WINHTTP_HEADER_NAME_BY_INDEX,buf,&len,
					WINHTTP_NO_HEADER_INDEX);
				TCHAR *s=StrStrI(buf,L"Checksum:");
				TCHAR *v=StrStrI(buf,L"Version:");
				if(s){
					s+=10;
					TCHAR *p=StrChr(s,L'\n');
					if(p)
						*p=0;
					swscanf_s(s,L"%d",&checksum);
				}
				if(v){
					v+=9;
					TCHAR *p=StrChr(v,L'\n');
					if(p)
						*p=0;
					swscanf_s(v,L"%d",&version);
				}
				free(buf);
			}
		}
	}
}